package com.oralce.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.oralce.entity.UserEntity;
import com.oralce.service.UserService;
import com.oralce.service.impl.UserServiceImpl;

public class UserLeiServlet extends HttpServlet {
	static UserService userService = new UserServiceImpl();
	private static ObjectMapper mapper = new ObjectMapper();
	@Override
	protected void service(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
		arg0.setCharacterEncoding("UTF-8");
		arg1.setCharacterEncoding("UTF-8");
		String method=arg0.getParameter("method");
		if("save".equals(method)) {
			save(arg0,arg1);
		}else if("delete".equals(method)) {
			delete(arg0,arg1);
		}else if("edit".equals(method)) {
			edit(arg0,arg1);
		}else if("query".equals(method)) {
			query(arg0,arg1);
		}
	}
	private void save(HttpServletRequest arg0, HttpServletResponse arg1) throws JsonParseException, JsonMappingException, IOException {
			UserEntity userEntity=mapper.readValue(arg0.getParameter("data"), UserEntity.class);
			userService.addUpdate(userEntity);
			PrintWriter out = arg1.getWriter();
			out.print("success");

	}
	private void delete(HttpServletRequest arg0, HttpServletResponse arg1) throws IOException {
		Long id = Long.valueOf(arg0.getParameter("id"));
		userService.delete(id);
		PrintWriter out = arg1.getWriter();
		out.print("success");

		
	}
	private void edit(HttpServletRequest arg0, HttpServletResponse arg1) throws IOException {
		Long id = Long.valueOf(arg0.getParameter("id"));
			UserEntity user = userService.getById(id);
			PrintWriter out = arg1.getWriter();
			out.print(mapper.writeValueAsString(user));
		
	}
	private void query(HttpServletRequest arg0, HttpServletResponse arg1) throws IOException {
		PrintWriter out = arg1.getWriter();
		out.print(mapper.writeValueAsString(userService.listAll()));
		
	}
	
	
}
